package com.sense.kukoo.biz_media.vm

import android.util.Log
import androidx.lifecycle.MutableLiveData
import com.sense.kukoo.common.event.LoginSuccessEvent
import com.sense.kukoo.common.media.Kukoo
import com.sense.kukoo.common.media.bean.LocalMediaListItemBean
import com.sense.kukoo.common.media.watcher.UserWatcher
import com.sense.kukoo.common.mvvm.model.BaseMvvmModel
import com.sense.kukoo.common.mvvm.vm.BaseViewModel
import com.sense.kukoo.common.repo.Repo
import com.sense.kukoo.common.repo.biz.SeekBarProgressBean
import com.sense.kukoo.common.repo.http.bean.CommentRecordBean
import com.sense.kukoo.common.repo.http.bean.ContentInfoBean
import com.sense.kukoo.common.repo.http.bean.ContentListeningBean
import com.sense.kukoo.common.repo.http.bean.IndexContentBean
import com.sense.kukoo.lib_logger.LoggerManager
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

class MediaDescriptionViewModel: BaseViewModel() {

    private val TAG: String = javaClass.simpleName

    private var mCurrentMusic:LocalMediaListItemBean? = null
    private var mCurrentState:Int = UserWatcher.MusicStateWatcher.STATE_NOT_PLAYING
    private var mIsFollow: Boolean = false
    private var mFlagToLink: Boolean = false
    private var mCurrentContentId: Long = -1L
    private var mTabPosition: Int = 0

    private val mSeekBarProgressBean = SeekBarProgressBean(0,0)

    val action_finish: MutableLiveData<Boolean> = MutableLiveData()
    val action_toChannel: MutableLiveData<String> = MutableLiveData()
    val action_toPlayList: MutableLiveData<Boolean> = MutableLiveData()
    val action_showLoginDialog: MutableLiveData<Boolean> = MutableLiveData()
    val action_showShareDialog: MutableLiveData<Boolean> = MutableLiveData()
    val action_showSettingDialog: MutableLiveData<Boolean> = MutableLiveData()
    val action_showAddCommentDialog: MutableLiveData<Boolean> = MutableLiveData()
    val action_networkError: MutableLiveData<Boolean> = MutableLiveData()
    val action_newComment: MutableLiveData<CommentRecordBean> = MutableLiveData()
    val action_newMusic: MutableLiveData<Boolean> = MutableLiveData()
    val data_contentInfo:MutableLiveData<ContentInfoBean> = MutableLiveData()
    val data_contentListening:MutableLiveData<ContentListeningBean> = MutableLiveData()
    val data_isShowMusicPlayer: MutableLiveData<Boolean> = MutableLiveData()
    val data_isPlayerBtnPause: MutableLiveData<Boolean> = MutableLiveData()
    val data_playerTimeCurrent: MutableLiveData<String> = MutableLiveData()
    val data_playerTimeTotal: MutableLiveData<String> = MutableLiveData()
    val data_playerSeekBar: MutableLiveData<SeekBarProgressBean> = MutableLiveData()
    val data_btnFollowState: MutableLiveData<Int> = MutableLiveData()
    val data_btnLikeState: MutableLiveData<Boolean> = MutableLiveData()
    val data_btnLikeNumber: MutableLiveData<Int> = MutableLiveData()
    val data_btnShareNumber: MutableLiveData<Int> = MutableLiveData()
    val data_btnCommentNumber: MutableLiveData<Int> = MutableLiveData()

    companion object{
        val STATE_FOLLOW_GONE = 0
        val STATE_FOLLOW_OFF = 1
        val STATE_FOLLOW_ON = 2

        val POSITION_DESCRIPTION = 0
        val POSITION_COMMENTS = 1
    }

    override fun createModel(): BaseMvvmModel? = null

    fun setFromData(id: Long){
        mCurrentContentId = id
    }

    fun setTabPosition(position: Int){
        mTabPosition = position
    }

    override fun initData() {
        Kukoo.watcher.register(mlistener)
        EventBus.getDefault().register(this)
        getContentInfo()
    }

    fun onBtnBackClick(){
        action_finish.postValue(true)
    }

    fun onBtnChannelClick(){
        action_toChannel.postValue("${data_contentInfo.value!!.userId}")
    }

    fun onBtnFollowClick(){
        if (!Repo.login.isLogin()) {
            action_showLoginDialog.postValue(true)
        } else {
            subscription()
        }
    }

    fun onBtnShareClick(){
        action_showShareDialog.postValue(true)
    }

    fun onBtnListenNowClick(){
        val contentInfo = data_contentInfo.value!!
        val music = LocalMediaListItemBean(IndexContentBean.formate(contentInfo))
        Kukoo.input.play(music)
    }

    fun OnBtnMediaSettingClick(){
        action_showSettingDialog.postValue(true)
    }

    fun OnBtnMediaBackwardClick(){
        Kukoo.input.seekBy(-15*1000)
    }

    fun OnBtnMediaForwardClick(){
        Kukoo.input.seekBy(30*1000)
    }

    fun OnBtnMediaPlayClick(){
        LoggerManager.d(TAG, "ivBtnMediaPlay.setOnClickListener state=${mCurrentState}")
        when (mCurrentState) {
            UserWatcher.MusicStateWatcher.STATE_PREPARE,
            UserWatcher.MusicStateWatcher.STATE_ERROR_RETRYING,
            UserWatcher.MusicStateWatcher.STATE_SEEKING,
            UserWatcher.MusicStateWatcher.STATE_PLAYING ->{
                Kukoo.input.pause()
            }
            UserWatcher.MusicStateWatcher.STATE_PAUSE ->{
                Kukoo.input.start()
            }
            else ->{
                LoggerManager.e(TAG, "iv_btn_play.setOnClick state=${mCurrentState} 不响应")
            }
        }
    }

    fun OnBtnMediaPlaylistClick(){
        action_toPlayList.postValue(true)
    }

    fun OnBtnAddCommentClick(){
        if (!Repo.login.isLogin()) {
            action_showLoginDialog.postValue(true)
        } else {
            action_showAddCommentDialog.postValue(true)
        }
    }

    fun OnBtnLikeClick(){
        if (!Repo.login.isLogin()) {
            action_showLoginDialog.postValue(true)
        } else {
            switchLike()
        }
    }

    fun getContentInfo(){
        toView(ACTION_SHOW_DIALOG)
        val onError: (error: Throwable) -> Unit = {
            it.printStackTrace()
            action_networkError.postValue(true)
            toView(ACTION_HIDE_DIALOG)
        }
        request(onError) {
            val contentInfo = Repo.http.contentInfo(mCurrentContentId)
            val contentInfoData: ContentInfoBean
            if (contentInfo.isSuccess()) {
                contentInfoData = contentInfo.data!!
                data_contentInfo.postValue(contentInfoData)
                //
                mIsFollow = contentInfoData.isFollow()
                val userId = Repo.user.get()?.id ?: -1
                if(userId == contentInfoData.userId){
                    data_btnFollowState.postValue(STATE_FOLLOW_GONE)
                } else {
                    data_btnFollowState.postValue( if (mIsFollow) STATE_FOLLOW_ON else STATE_FOLLOW_OFF )
                }
                //
                data_btnLikeState.postValue(contentInfoData.isLiked())
                data_btnLikeNumber.postValue(contentInfoData.likeNum)
                data_btnCommentNumber.postValue(contentInfoData.commentNum)
                data_btnShareNumber.postValue(contentInfoData.shareNum)

                //
                val contentListening = Repo.http.contentListening(contentInfoData.id)
                if (contentListening.isSuccess()) {
                    data_contentListening.postValue(contentListening.data!!)
                } else {
                    Log.e(TAG, "result=" + contentListening.msg)
                    action_networkError.postValue(true)
                }
            } else {
                Log.e(TAG, "result=" + contentInfo.msg)
                action_networkError.postValue(true)
            }
            toView(ACTION_HIDE_DIALOG)
        }
    }

    fun subscription(){
        toView(ACTION_SHOW_DIALOG)
        request {
            val userId = data_contentInfo.value!!.userId
            val subscription = Repo.http.subscription(userId)
            if (subscription.isSuccess()) {
                mIsFollow = !mIsFollow
                data_btnFollowState.postValue( if (mIsFollow) STATE_FOLLOW_ON else STATE_FOLLOW_OFF )
            } else {
                Log.e(TAG, "result=" + subscription.msg)
                subscription.msg.let { sendHintMessage(it) }
            }
            toView(ACTION_HIDE_DIALOG)
        }
    }

    fun switchLike(){
        toView(ACTION_SHOW_DIALOG)
        request {
            val contentInfo = data_contentInfo.value!!
            val isLike = data_btnLikeState.value == true
            val like = Repo.http.like(contentInfo.id, contentInfo.userId)
            if (like.isSuccess()) {
                val newLike = !isLike
                data_btnLikeState.postValue(newLike)
                if (newLike) {
                   data_btnLikeNumber.postValue((data_btnLikeNumber.value ?: 0) + 1)
                } else {
                    var num = (data_btnLikeNumber.value ?: 0) - 1
                    num = if(num < 0) 0 else num
                    data_btnLikeNumber.postValue(num)
                }
            } else {
                Log.e(TAG, "result=" + like.msg)
                like.msg.let { sendHintMessage(it) }
            }
            toView(ACTION_HIDE_DIALOG)
        }
    }

    fun onAddComment(text: String){
        toView(ACTION_SHOW_DIALOG)
        request {
            val contentInfo = data_contentInfo.value!!
            val commentSave = Repo.http.commentSave(contentInfo.id, contentInfo.userId, text, 0, 0)
            if (commentSave.isSuccess()) {
                //保存评论成功
                commentSave.data?.let { newComment ->
                    action_newComment.postValue(newComment)
                    data_btnCommentNumber.postValue((data_btnCommentNumber.value ?: 0) + 1)
                }
            } else {
                Log.e(TAG, "result=" + commentSave.msg)
                commentSave.msg.let { sendHintMessage(it) }
            }
            toView(ACTION_HIDE_DIALOG)
        }
    }

    fun onShareSuccess(){
        request {
            val contentInfo = data_contentInfo.value!!
            val result = Repo.http.shareSuccess(contentInfo.id)
            if (result.isSuccess()) {
                //保存评论成功
                result.data?.let {
                    val num = data_btnShareNumber.value ?: 0
                    data_btnShareNumber.postValue(num + 1)
                }
            } else {
                Log.e(TAG, "result=" + result.msg)
                result.msg.let { sendHintMessage(it) }
            }
        }
    }

    fun getCurrentContentId(): Long = mCurrentContentId

    override fun onCleared() {
        Kukoo.watcher.unregister(mlistener)
        EventBus.getDefault().unregister(this)
        super.onCleared()
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onMessageEvent(event: LoginSuccessEvent) {
        getContentInfo()
    }

    private val mlistener = object : UserWatcher.MusicStateWatcher{

        override fun onMusicChanged(music: LocalMediaListItemBean) {
            LoggerManager.d(TAG, "onMusicChanged - music.idOfBooks()=${music.idOfBooks()}")
            mCurrentMusic = music
            if(mFlagToLink){
                if (mCurrentMusic!!.isDefMusic()) {
                    data_isShowMusicPlayer.postValue(false)
                } else {
                    if(mTabPosition == POSITION_DESCRIPTION){
                        data_isShowMusicPlayer.postValue(true)
                        //刷新页面
                        mCurrentContentId = music.idOfChapter()
                        getContentInfo()
                        action_newMusic.postValue(true)
                    } else if(mTabPosition == POSITION_COMMENTS){
                        data_isShowMusicPlayer.postValue(false)
                        //进入到下一首，但暂停
                        Kukoo.input.pause()
                    }

                }
            } else {
                if(mCurrentMusic != null && mCurrentContentId == mCurrentMusic?.idOfChapter()){
                    //相同的音乐
                    data_isShowMusicPlayer.postValue(true)
                    mFlagToLink = true
                } else {
                    //不同的
                    data_isShowMusicPlayer.postValue(false)
                }
            }
        }

        override fun onPlayTimeChanged(currentInt:Int, totalInt:Int, current:String, total:String) {
            data_playerTimeCurrent.postValue(current)
            data_playerTimeTotal.postValue(total)
            //
            mSeekBarProgressBean.setData(currentInt, totalInt)
            data_playerSeekBar.postValue(mSeekBarProgressBean)
        }

        override fun onPlayPercentChanged(percent: Int) {}

        override fun onPlayStateChanged(state: Int) {
            mCurrentState = state
            LoggerManager.d(TAG, "onPlayStateChanged() state=${state}")
            when (state) {
                UserWatcher.MusicStateWatcher.STATE_ERROR_RETRYING,
                UserWatcher.MusicStateWatcher.STATE_PREPARE,
                UserWatcher.MusicStateWatcher.STATE_PLAYING ->{
                    //播放中
                    data_isPlayerBtnPause.postValue(true)
                }
                UserWatcher.MusicStateWatcher.STATE_PAUSE ->{
                    //暂停中
                    data_isPlayerBtnPause.postValue(false)
                }
                else ->{
                    LoggerManager.e(TAG, "mlistener.onPlayStateChanged state=${state} 不响应")
                }
            }
        }

        override fun onPlaySpeedChanged(speed: Float) {}

        override fun onPlayListChanged() {}
    }

}